package middleware

import (
	"com.haojuetrace/actualCombat/common"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strings"
)

/*
	gin中间件
	用于检查token的有效性
*/
//AuthMiddleware 检测token是否过期 检测token权限
func AuthMiddleware(c *gin.Context) {
	db := common.GetDb()

	tokenString := c.GetHeader("Authorization")
	//log.Println(tokenString)
	if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer") {
		log.Println("tokenString is null or no beginning Bearer")
		c.JSON(http.StatusUnauthorized, gin.H{
			"code": 401,
			"msg":  "权限不足",
		})
		c.Abort()
		return

	}
	tokenString = tokenString[7:]
	//log.Println(tokenString)
	//解析token
	token, users, err := common.ParseToken(tokenString)
	if err != nil {
		log.Println(err.Error())
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "token 已过期，请重新登录",
		})
		c.Abort()
		return

	}
	if !token.Valid {
		//log.Println(token.Valid)
		c.JSON(http.StatusUnauthorized, gin.H{
			"code": 401,
			"msg":  "权限不足",
		})
		c.Abort()
		return

	}
	//检测用户是否存在
	log.Println(users.UserId)
	exist, user := common.UserExist("id", users.UserId, db)

	if !exist {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code": 401,
			"msg":  "用户已不存在，权限不足",
		})
		c.Abort()
		return
	}

	//用户存在 将user的信息写入上下文
	c.Set("user", user)
	c.Next()
}
